package cn.changeforyou.web.cloud.rpc.service.common;

import cn.changeforyou.web.cloud.webBase.utils.bean.BeanCopierUtil;
import cn.changeforyou.web.cloud.webBase.utils.bean.GenericityUtil;
import cn.changeforyou.web.cloud.rpc.common.model.BaseDTO;
import com.baomidou.mybatisplus.extension.service.IService;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public interface BaseService<VO, DTO extends BaseDTO> extends IService<VO>, Serializable {
    ConcurrentHashMap<Class, Class> DTO_CLASS_CACHE = new ConcurrentHashMap<>();

    default List<DTO> listDTO() {
        List<VO> list = this.list();
        if (list.isEmpty()) {
            return new ArrayList<>();
        }
        Class dtoClass = DTO_CLASS_CACHE.get(this.getClass());
        if (null == dtoClass) {
            dtoClass = GenericityUtil.findGenericityFromParentOrGrandFather(this.getClass(), BaseService.class, 1);
            if (null != dtoClass) {
                DTO_CLASS_CACHE.put(this.getClass(), dtoClass);
            }
        }
        return BeanCopierUtil.copyList(list, dtoClass);
    }
}
